package com.family.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.family.domain.Area;
import com.family.domain.Authority;
import com.family.domain.Desk;
import com.family.domain.Evaluate;
import com.family.domain.Food;
import com.family.domain.FoodType;
import com.family.domain.Order;
import com.family.domain.Role;
import com.family.domain.SubFood;
import com.family.domain.SubOrder;
import com.family.domain.User;
import com.family.inter.IArea;
import com.family.inter.IAuthority;
import com.family.inter.IAuthority_role;
import com.family.inter.IDesk;
import com.family.inter.IEvaluate;
import com.family.inter.IFood;
import com.family.inter.IFoodtype;
import com.family.inter.IOrder;
import com.family.inter.IRole;
import com.family.inter.IUser;
import com.family.jsontmp.DeskMsg;
import com.family.jsontmp.JsonBean;
import com.family.jsontmp.JsonComboxBean;
import com.family.jsontmp.JsonList;
import com.family.jsontmp.JsonMsg;
import com.family.jsontmp.tree;
import com.family.tools.DateFormatUtils;

@RestController
public class JsonAction {

    @Resource
    IUser iuser;

    @Resource
    IAuthority iautnority;

    @Resource
    IRole irole;

    @Resource
    IAuthority_role iautrole;

    @Resource
    IFoodtype ifoodtype;

    @Resource
    IFood ifood;

    @Resource
    IArea iarea;

    @Resource
    IDesk idesk;

    @Resource
    IOrder iorder;

    @Resource
    IEvaluate ievaluate;


    @RequestMapping("/List")
    public List<User> getUserList(HttpServletRequest request, HttpServletResponse response)
    {

        List<User> list = iuser.getUserList();

//		String jsonArray = JSONArray.toJSONString(list);
//		System.out.println("==="+jsonArray);

//	    response.setContentType("text/html;charset=utf-8");
//	    PrintWriter out = response.getWriter();
//	    out.print(jsonArray);
//	    out.close();

        return list;
    }

    @RequestMapping("/loadComboxData")
    public List<JsonComboxBean> loadComboxData(ModelMap model,HttpServletResponse response)
    {
        int flag=0;
        List<JsonComboxBean> arr = new ArrayList<JsonComboxBean>();
        List<Role> roleList = irole.getRoleList();

        for(Role role :roleList){
            JsonComboxBean item = new  JsonComboxBean();
            item.setValue(role.getId());
            item.setText(role.getRole_name());
            arr.add(item);
        }

        return arr;
    }

    @RequestMapping("/loadFoodComData")
    public List<JsonComboxBean> loadFoodComData()
    {
        List<JsonComboxBean> arr = new ArrayList<JsonComboxBean>();
        List<FoodType> roleList = ifoodtype.getFoodTypeList();

        for(FoodType tp :roleList){
            JsonComboxBean item = new  JsonComboxBean();
            item.setValue(tp.getId());
            item.setText(tp.getTypename());
            arr.add(item);
        }

        return arr;
    }

    @RequestMapping("/loadDeskComData")
    public List<JsonComboxBean> loadDeskComData()
    {
        List<JsonComboxBean> arr = new ArrayList<JsonComboxBean>();
        List<Area> areaList = iarea.getAreaList();

        for(Area tp :areaList){
            JsonComboxBean item = new  JsonComboxBean();
            item.setValue(tp.getId());
            item.setText(tp.getAreaname());
            arr.add(item);
        }

        return arr;
    }

    @RequestMapping("/foodTypeList")
    public JsonBean getFoodTypeList(HttpServletRequest request, HttpServletResponse response)
    {

        List<FoodType> foodList = ifoodtype.getFoodTypeList();

        JsonBean json = new JsonBean();
        json.setTotal(String.valueOf(foodList.size()));
        json.setRows(foodList);

        return json;
    }

    @RequestMapping("/areaList")
    public List<Area> areaList()
    {

        List<Area> areaList = iarea.getAreaList();

        return areaList;
    }

    @RequestMapping("/deskList")
    public List<Desk> deskList(String id)
    {

        List<Desk> deskList = idesk.getDeskListById(id);

        return deskList;
    }

    @RequestMapping("/deskListSort")
    public List<Desk> deskListSort(String id)
    {

        List<Desk> deskList = idesk.getDeskNumById(id);

        return deskList;
    }

    @RequestMapping("/getEvaluate")
    public Evaluate getEvaluate(String orgid)
    {
        Evaluate ev = ievaluate.getEvaluateByorgId(orgid);
        return ev;
    }

    @RequestMapping("/deskNoGroup")
    public List<Desk> deskNoGroup()
    {
        List<Desk> deskList = idesk.getDeskNoGroup();
        return deskList;
    }

    @RequestMapping("/foodList")
    public List<Food> foodList()
    {

        List<Food> foodList = ifood.getFoodList();

        return foodList;
    }

    @RequestMapping("/foodListnoGroup")
    public List<Food> foodListnoGroup()
    {

        List<Food> foodList = ifood.getFoodListNoGroup();

        return foodList;
    }

    @RequestMapping("/foodListByType")
    public List<Food> foodListByType(String id)
    {

        List<Food> foodList = ifood.getFoodListByType(id);

        return foodList;
    }

    @RequestMapping("/getFoodByLike")
    public List<Food> getFoodByLike(String foodname)
    {
        List<Food> foodList = ifood.getFoodByLike(foodname);
        for(Food f:foodList)
        {
            f.setScore("1");
        }

        return foodList;
    }

    @RequestMapping("/p_getFoodByLike")
    public List<Food> p_getFoodByLike(String foodname)
    {
        List<Food> foodList = ifood.getFoodByLike(foodname);
        for(Food f:foodList)
        {
            String imglist=f.getImage();
            String[] imgarr=imglist.split(",");
            f.setImage(imgarr[0]);
        }
        return foodList;
    }

    @RequestMapping("/getFoodByLikeNoGroup")
    public List<Food> getFoodByLikeNoGroup(String foodname)
    {
        List<Food> foodList = ifood.getFoodByLikeNoGroup(foodname);
        for(Food f:foodList)
        {
            f.setScore("1");
        }

        return foodList;
    }

    @RequestMapping("/foodListGroup")
    public JsonList foodListGroup(String id)
    {

        JsonList jlist = new JsonList();

        List<Food> trim = new ArrayList<Food>();

        List<Food> group = ifood.getFoodListByType(id);

        List<Food> all = ifood.getFoodList();

        for(Food food:all)
        {
            if(!group.contains(food))
            {
                trim.add(food);
            }
        }
        jlist.setAllList(trim);
        jlist.setGroupList(group);

        return jlist;
    }



    @RequestMapping("/roleList")
    public List<Role> getRoleList(HttpServletRequest request, HttpServletResponse response)
    {

        List<Role> list = irole.getRoleList();

//		String jsonArray = JSONArray.toJSONString(list);
        //System.out.println(jsonArray);

//	    response.setContentType("text/html;charset=utf-8");
//	    PrintWriter out = response.getWriter();
//	    out.print(jsonArray);
//	    out.close();

        return list;
    }
    @RequestMapping("/loadMenuTree1")
    public ArrayList<tree> loadMenuTree(String role_id,ModelMap model,HttpSession session,HttpServletResponse response)
    {

        User user = (User) session.getAttribute("user");

        List<Authority> arrList = iautrole.selectAutListByRoleId(user.getRole_id());

        ArrayList<tree> arr = new ArrayList<tree>();
        tree root = new  tree();

        showMenu("root",root,arrList);

        //System.out.println("load tree");

        arr.add(root);

//		return root;

        String jsonArray = JSONArray.toJSONString(arr);
        System.out.println(jsonArray);
//	    response.setContentType("text/html;charset=utf-8");
//	    PrintWriter out = response.getWriter();
//	    out.print(jsonArray);
//	    out.close();

        return arr;
    }

    public void showMenu(String parent_id,tree tree,List<Authority> arrRole)
    {
        List<Authority> arr = iautnority.getAuthorityList(parent_id);
        if(arr.size()>0)
        {
            Authority root = iautnority.getAuthorityById(parent_id);
            List<tree> child = new ArrayList<tree>();

            tree.setId(root.getA_url());
            tree.setText(root.getA_name());

            for(Authority aut:arr)
            {
                tree t = new tree();
                showMenu(aut.getId(),t,arrRole);
                //System.out.println("list="+t.getText());
                if(t.getId()!=null)
                {
                    child.add(t);
                }else if(aut.getA_url()==null)
                {
                    if(t.getChildren()!=null)
                    {
                        child.add(t);
                    }

                }
                else
                {
                    //System.out.println("sub="+t.getText());
                }
            }
            if(child.size()>0)
                tree.setChildren(child);

        }
        else
        {
            Authority aut = iautnority.getAuthorityById(parent_id);

            if(arrRole.contains(aut)||aut.getA_url().trim().length()==0)
            {
                tree.setChecked(true);
                tree.setId(aut.getA_url());
                tree.setText(aut.getA_name());
                //System.out.println("not null="+aut.getA_name());
            }else
            {
                tree = null;
                //System.out.println("null="+aut.getA_name()+"url=["+aut.getA_url().length()+"]");
            }


        }

    }

    @RequestMapping("/showOrderDetail")
    public JsonBean showOrderDetail(String orderid)
    {
        int sum=0;

        JsonBean data = new JsonBean();
        List<SubFood> arr = new ArrayList<SubFood>();
        Order order = iorder.getOrderById(orderid);
        if(order==null)
        {
            data.setTotal("0");
            return data;
        }

        List<SubFood>  list = ifood.getFoodListByOrderid(order.getId());
        for(SubFood food:list)
        {
            String[] img = food.getImage().split(",");
            food.setImage(img[0]);

            Evaluate ev= ievaluate.getEvaluateByorgId(food.getOrderid());
            if(ev!=null)
            {
                food.setScore("1");
            }else
            {
                food.setScore("0");
            }

            arr.add(food);

            sum+=Integer.parseInt(food.getPrice())*Integer.parseInt(food.getCount());
        }



        data.setRows(arr);
        data.setTotal(String.valueOf(arr.size()));


        List<SubFood> foot = new ArrayList<SubFood>();

        SubFood sub = new SubFood();
        sub.setFoodname("合计:");
        sub.setPrice(String.valueOf(sum));
        sub.setId("sum");
        sub.setOrderid(order.getId());
        sub.setCount("元");
        foot.add(sub);
        data.setFooter(foot);



        return data;
    }

    @RequestMapping("/showCar")
    public JsonBean showCar(String deskid)
    {
        int sum=0;

        Desk desk = idesk.getDeskById(deskid);
        if(desk!=null)
        {
            if(desk.getOthid()!=null && desk.getOthid().trim().length()>0)
            {
                deskid=desk.getOthid();
            }
        }


        JsonBean data = new JsonBean();
        List<SubFood> arr = new ArrayList<SubFood>();
        Order order = iorder.getOrderByDeskId(deskid);
        if(order==null)
        {
            data.setTotal("0");
            return data;
        }

        List<SubFood>  list = ifood.getFoodListByOrderid(order.getId());
        for(SubFood food:list)
        {
            String[] img = food.getImage().split(",");
            food.setImage(img[0]);

            Evaluate ev= ievaluate.getEvaluateByorgId(food.getOrderid());
            if(ev!=null)
            {
                food.setScore("1");
            }else
            {
                food.setScore("0");
            }

            arr.add(food);

            sum+=Integer.parseInt(food.getPrice())*Integer.parseInt(food.getCount());
        }



        data.setRows(arr);
        data.setTotal(String.valueOf(arr.size()));


        List<SubFood> foot = new ArrayList<SubFood>();

        SubFood sub = new SubFood();
        sub.setFoodname("合计:");
        sub.setPrice(String.valueOf(sum));
        sub.setId("sum");
        sub.setOrderid(order.getId());
        sub.setCount("元");
        foot.add(sub);
        data.setFooter(foot);



        return data;
    }

    @RequestMapping("/getAllOrder")
    public JsonBean getAllOrder(String sdate,String edate,String flag,String desknum)
    {
        int sum=0;
        Map map = new HashMap<String, String>();
        map.put("sdate", DateFormatUtils.parseDate(sdate));
        map.put("edate", DateFormatUtils.parseDate(edate));
        map.put("flag", flag);
        map.put("desknum", desknum);

        JsonBean data = new JsonBean();

        List<SubOrder> tmparr = iorder.getAllOrder(map);
        for(SubOrder order:tmparr)
        {
            String tdate=order.getOrgdate();
            String ttime=order.getOrgtime();
            order.setOrgdate(DateFormatUtils.changeDate(tdate));
            order.setOrgtime(DateFormatUtils.changeTime(tdate,ttime));

            if(order.getOrgamt()!=null && order.getOrgamt().trim().length()>0)
            {
                sum+=Integer.parseInt(order.getOrgamt());
            }
        }

        data.setRows(tmparr);
        data.setTotal(String.valueOf(tmparr.size()));

        List<SubOrder> foot = new ArrayList<SubOrder>();

        SubOrder tmp = new SubOrder();
        tmp.setId("sum");
        tmp.setOrgtime("合计：");
        tmp.setOrgamt(String.valueOf(sum));
        tmp.setDname("订单数：");
        tmp.setCount(String.valueOf(tmparr.size()));
        foot.add(tmp);
        data.setFooter(foot);

        return data;
    }

    @RequestMapping("/getOrderCount")
    public JsonBean getOrderCount(String sdate,String edate)
    {
        int sum=0;
        int count=0;

        Map map = new HashMap<String, String>();
        map.put("sdate", DateFormatUtils.parseDate(sdate));
        map.put("edate", DateFormatUtils.parseDate(edate));

        JsonBean data = new JsonBean();

        List<SubOrder> tmparr = iorder.getOrderCount(map);
        for(SubOrder order:tmparr)
        {
            String tdate=order.getOrgdate();
            order.setOrgdate(DateFormatUtils.changeDate(tdate));

            if(order.getOrgamt()!=null && order.getOrgamt().trim().length()>0)
            {
                sum+=Float.valueOf(order.getOrgamt()).intValue();
            }

            count+=Integer.parseInt(order.getCount());
        }

        data.setRows(tmparr);
        data.setTotal(String.valueOf(tmparr.size()));

        List<SubOrder> foot = new ArrayList<SubOrder>();

        SubOrder tmp = new SubOrder();

        tmp.setOrgdate("合计：");
        tmp.setCount(String.valueOf(count));
        tmp.setOrgamt(String.valueOf(sum));
        foot.add(tmp);
        data.setFooter(foot);

        return data;
    }

    @RequestMapping("/show_deskstat")
    public List<Desk> show_deskstat(String areaid)
    {
        List<Desk> dlist = idesk.getDeskListById(areaid);
        return dlist;
    }

    @RequestMapping("/getFoodEvSort")
    public List<Food> getFoodEvSort(String sdate,String edate,String foodname)
    {

        Map map = new HashMap<String, String>();
        if(sdate==null && edate==null)
        {
            map.put("sdate", "19000101");
            map.put("edate", DateFormatUtils.getCurDate());
        }
        else
        {
            map.put("sdate", DateFormatUtils.parseDate(sdate));
            map.put("edate", DateFormatUtils.parseDate(edate));
        }

        map.put("foodname", foodname);

        List<Food> dlist = ifood.getFoodEvSort(map);


        return dlist;
    }


    @RequestMapping("/getEvaluateList")
    public List<Evaluate> getEvaluateList(String sdate,String edate,String foodid,String score)
    {

        Map map = new HashMap<String, String>();

        map.put("sdate", DateFormatUtils.parseDate(sdate));
        map.put("edate", DateFormatUtils.parseDate(edate));
        map.put("foodid", foodid);
        map.put("score", score);

        List<Evaluate> dlist = ievaluate.getEvaluateList(map);

        return dlist;
    }


    @RequestMapping("/getFoodCount")
    public List<Food> getFoodCount(String sdate,String edate,String foodname)
    {

        Map map = new HashMap<String, String>();
        if(sdate==null && edate==null)
        {
            map.put("sdate", "19000101");
            map.put("edate", DateFormatUtils.getCurDate());
        }
        else
        {
            map.put("sdate", DateFormatUtils.parseDate(sdate));
            map.put("edate", DateFormatUtils.parseDate(edate));
        }
        map.put("foodname", foodname);
        List<Food> dlist = ifood.getFoodCount(map);


        return dlist;
    }

    @RequestMapping("/p_getMsgNotifyJson")
    public JsonMsg p_getMsgNotify(String key,HttpServletRequest request)
    {
        ServletContext application=request.getSession().getServletContext();
        HashMap map = (HashMap)application.getAttribute("notify");

        JsonMsg jsonMsg = new JsonMsg();
        List<DeskMsg> msgList= new ArrayList<DeskMsg>();

        if(map!=null)
        {
            Set set = map.keySet();


            Iterator it=  set.iterator();
            while(it.hasNext())
            {
                DeskMsg msg = new DeskMsg();

                String did = it.next().toString();
                Desk desk = idesk.getDeskById(did);
                String dmsg = map.get(did).toString();

                msg.setIdnum(desk.getIdnum());
                msg.setDmsg(dmsg);
                msg.setDeskid(did);

                msgList.add(msg);

                map.remove(did);
            }

            jsonMsg.setDeskmsg(msgList);

        }

        StringBuffer sb = new StringBuffer();

        List<Area> arrList = iarea.getAreaList();
        for(Area area:arrList)
        {
            sb.append(area.getAreaname()+":");
            sb.append(String.valueOf(idesk.getAreaCount(area.getId())));
            sb.append("&nbsp;&nbsp;");
        }
        jsonMsg.setAreaDetail(sb.toString());


        if (Application.key.equals(key)){
            jsonMsg.setFlag("1");

        }else
        {
            jsonMsg.setFlag("0");
        }

        return jsonMsg;

    }

}
